<template>
  <view class="settings-container">
    <!-- 顶部导航 -->
    <view class="settings-header">
      <button class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i>
      </button>
      <text class="header-title">设置</text>
    </view>

    <!-- 设置内容 -->
    <view class="settings-content">
      <!-- 账户设置 -->
      <view class="settings-section">
        <text class="section-title">账户设置</text>
        <view class="settings-list">
          <view class="setting-item" @click="editProfile">
            <view class="setting-left">
              <i class="setting-icon fas fa-user"></i>
              <text class="setting-label">编辑个人资料</text>
            </view>
            <i class="setting-arrow fas fa-chevron-right"></i>
          </view>
          <view class="setting-item" @click="changePassword">
            <view class="setting-left">
              <i class="setting-icon fas fa-lock"></i>
              <text class="setting-label">修改密码</text>
            </view>
            <i class="setting-arrow fas fa-chevron-right"></i>
          </view>
        </view>
      </view>

      <!-- 应用设置 -->
      <view class="settings-section">
        <text class="section-title">应用设置</text>
        <view class="settings-list">
          <view class="setting-item" @click="checkUpdate">
            <view class="setting-left">
              <i class="setting-icon fas fa-download"></i>
              <text class="setting-label">检查更新</text>
            </view>
            <view class="setting-right">
              <text class="update-status" :class="updateStatus">{{ updateStatusText }}</text>
              <i class="setting-arrow fas fa-chevron-right"></i>
            </view>
          </view>
          <view class="setting-item" @click="clearCache">
            <view class="setting-left">
              <i class="setting-icon fas fa-trash"></i>
              <text class="setting-label">清除缓存</text>
            </view>
            <view class="setting-right">
              <text class="cache-size">{{ cacheSize }}</text>
              <i class="setting-arrow fas fa-chevron-right"></i>
            </view>
          </view>
          <view class="setting-item" @click="exportData">
            <view class="setting-left">
              <i class="setting-icon fas fa-file-export"></i>
              <text class="setting-label">导出数据</text>
            </view>
            <i class="setting-arrow fas fa-chevron-right"></i>
          </view>
        </view>
      </view>

      <!-- 通知设置 -->
      <view class="settings-section">
        <text class="section-title">通知设置</text>
        <view class="settings-list">
          <view class="setting-item">
            <view class="setting-left">
              <i class="setting-icon fas fa-bell"></i>
              <text class="setting-label">推送通知</text>
            </view>
            <switch 
              :checked="settings.pushNotification" 
              @change="togglePushNotification"
              color="#7B68EE"
            />
          </view>
          <view class="setting-item">
            <view class="setting-left">
              <i class="setting-icon fas fa-envelope"></i>
              <text class="setting-label">邮件通知</text>
            </view>
            <switch 
              :checked="settings.emailNotification" 
              @change="toggleEmailNotification"
              color="#7B68EE"
            />
          </view>
        </view>
      </view>

      <!-- 隐私设置 -->
      <view class="settings-section">
        <text class="section-title">隐私设置</text>
        <view class="settings-list">
          <view class="setting-item">
            <view class="setting-left">
              <i class="setting-icon fas fa-eye"></i>
              <text class="setting-label">公开个人资料</text>
            </view>
            <switch 
              :checked="settings.publicProfile" 
              @change="togglePublicProfile"
              color="#7B68EE"
            />
          </view>
          <view class="setting-item">
            <view class="setting-left">
              <i class="setting-icon fas fa-search"></i>
              <text class="setting-label">允许搜索</text>
            </view>
            <switch 
              :checked="settings.allowSearch" 
              @change="toggleAllowSearch"
              color="#7B68EE"
            />
          </view>
        </view>
      </view>

      <!-- 关于 -->
      <view class="settings-section">
        <text class="section-title">关于</text>
        <view class="settings-list">
          <view class="setting-item" @click="viewAbout">
            <view class="setting-left">
              <i class="setting-icon fas fa-info-circle"></i>
              <text class="setting-label">关于应用</text>
            </view>
            <view class="setting-right">
              <text class="app-version">v{{ appVersion }}</text>
              <i class="setting-arrow fas fa-chevron-right"></i>
            </view>
          </view>
          <view class="setting-item" @click="viewPrivacy">
            <view class="setting-left">
              <i class="setting-icon fas fa-shield-alt"></i>
              <text class="setting-label">隐私政策</text>
            </view>
            <i class="setting-arrow fas fa-chevron-right"></i>
          </view>
          <view class="setting-item" @click="viewTerms">
            <view class="setting-left">
              <i class="setting-icon fas fa-file-contract"></i>
              <text class="setting-label">服务条款</text>
            </view>
            <i class="setting-arrow fas fa-chevron-right"></i>
          </view>
        </view>
      </view>

      <!-- 退出登录 -->
      <view class="settings-section">
        <view class="settings-list">
          <view class="setting-item logout-item" @click="logout">
            <view class="setting-left">
              <i class="setting-icon fas fa-sign-out-alt"></i>
              <text class="setting-label logout-text">退出登录</text>
            </view>
            <i class="setting-arrow fas fa-chevron-right"></i>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 下载进度弹窗 -->
    <uni-popup ref="downloadModal" type="center">
      <view class="download-modal">
        <view class="download-header">
          <text class="download-title">正在下载更新</text>
        </view>
        <view class="download-body">
          <view class="progress-container">
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: downloadProgress + '%' }"></view>
            </view>
            <text class="progress-text">{{ downloadProgress }}%</text>
          </view>
          <text class="download-tip">请勿关闭应用，下载完成后将自动安装</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { checkAppUpdate, getUpdateInfo } from '@/api/update'
import { clearLoginInfo, getCurrentUserId, getCurrentUserInfo } from '@/utils/auth'
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'

export default {
    components: {
        UniPopup
    },
  data() {
    return {
      settings: {
        pushNotification: true,
        emailNotification: false,
        publicProfile: true,
        allowSearch: true
      },
      updateStatus: 'idle', // idle, checking, available, latest
      updateStatusText: '检查更新',
      cacheSize: '0.5MB',
      appVersion: '1.0.0',
      isCheckingUpdate: false,
      downloadProgress: 0,
      isDownloading: false
    }
  },
  
  onLoad() {
    this.loadSettings()
    this.getAppVersion()
    this.calculateCacheSize()
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    getCurrentUserInfo() {
      return getCurrentUserInfo()
    },
    
    loadSettings() {
      try {
        const savedSettings = uni.getStorageSync('userSettings')
        if (savedSettings) {
          this.settings = { ...this.settings, ...JSON.parse(savedSettings) }
        }
      } catch (error) {
        console.error('加载设置失败:', error)
      }
    },
    
    saveSettings() {
      try {
        uni.setStorageSync('userSettings', JSON.stringify(this.settings))
      } catch (error) {
        console.error('保存设置失败:', error)
      }
    },
    
    getAppVersion() {
      // 获取应用版本信息
      // #ifdef APP-PLUS
      plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
        this.appVersion = widgetInfo.version
      })
      // #endif
      
      // #ifdef H5
      this.appVersion = '1.0.0'
      // #endif
    },
    
    calculateCacheSize() {
      // 计算缓存大小
      try {
        const cacheInfo = uni.getStorageInfoSync()
        const sizeInKB = cacheInfo.currentSize
        const sizeInMB = (sizeInKB / 1024).toFixed(1)
        this.cacheSize = `${sizeInMB}MB`
      } catch (error) {
        console.error('计算缓存大小失败:', error)
        this.cacheSize = '0.0MB'
      }
    },
    
    async checkUpdate() {
      if (this.isCheckingUpdate) return
      
      this.isCheckingUpdate = true
      this.updateStatus = 'checking'
      this.updateStatusText = '检查中...'
      
      try {
          
        // 获取本地当前版本
        let localVersion = '1.0.0'
        // #ifdef APP-PLUS
        localVersion = plus.runtime.version
        // #endif
        
        const res = await checkAppUpdate()
        const { latestVersion, downloadUrl, isForce, description } = res.data
        
        // 版本对比
        if (this.compareVersion(localVersion, latestVersion) < 0) {
          this.updateStatus = 'available'
          this.updateStatusText = '有新版本'
          
          uni.showModal({
            title: '发现新版本',
            content: `${description}\n\n当前版本：${localVersion}\n最新版本：${latestVersion}\n\n是否立即更新？`,
            confirmText: '立即更新',
            cancelText: '稍后再说',
            success: (res) => {
              if (res.confirm) {
                this.downloadAndInstall(downloadUrl, isForce, latestVersion)
              }
            }
          })
        } else {
          this.updateStatus = 'latest'
          this.updateStatusText = '已是最新版本'
          uni.showToast({
            title: '已是最新版本',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('检查更新失败:', error)
        // 错误已在 handleApiError 中处理
        
        this.updateStatus = 'error'
        this.updateStatusText = '检查失败'
        
        uni.showToast({
          title: '检查更新失败',
          icon: 'none'
        })
      } finally {
        this.isCheckingUpdate = false
      }
    },
    
    // 版本对比工具函数
    compareVersion(v1, v2) {
      const arr1 = v1.split('.').map(Number)
      const arr2 = v2.split('.').map(Number)
      for (let i = 0; i < Math.max(arr1.length, arr2.length); i++) {
        const num1 = arr1[i] || 0
        const num2 = arr2[i] || 0
        if (num1 > num2) return 1
        if (num1 < num2) return -1
      }
      return 0
    },
    
    // 下载并安装更新包
    downloadAndInstall(downloadUrl, isForce, latestVersion) {
      let retryCount = 0
      const maxRetries = 3
      
      const doDownload = () => {
        // 显示下载进度弹窗
        this.showDownloadProgress()
        
        const downloadTask = uni.downloadFile({
          url: downloadUrl,
          success: (downloadRes) => {
            this.hideDownloadProgress()
            
            // 验证文件完整性
            if (downloadRes.statusCode === 200 && downloadRes.tempFilePath) {
              // 调用uni-app的安装API（仅App端支持）
              plus.runtime.install(downloadRes.tempFilePath, {
                force: isForce // 是否强制覆盖安装
              }, () => {
                uni.showToast({ title: '更新完成，重启应用生效' })
                
                // 上报版本更新成功
                this.reportUpdate({
                  version: latestVersion,
                  platform: plus.os.name,
                  userId: getCurrentUserId(false) || 'unknown'
                }).catch(err => console.error('版本上报失败:', err))
                
                setTimeout(() => {
                  plus.runtime.restart() // 重启应用
                }, 1500)
              }, (error) => {
                uni.showToast({ title: '安装失败，请稍后重试', icon: 'none' })
              })
            } else {
              this.handleDownloadError()
            }
          },
          fail: this.handleDownloadError
        })
        
        // 监听下载进度
        downloadTask.onProgressUpdate((res) => {
          this.updateDownloadProgress(res.progress)
        })
      }
      
      this.handleDownloadError = () => {
        this.hideDownloadProgress()
        retryCount++
        
        if (retryCount <= maxRetries) {
          uni.showToast({ 
            title: `下载失败，正在重试... (${retryCount}/${maxRetries})`, 
            icon: 'none' 
          })
          setTimeout(doDownload, 2000)
        } else {
          uni.showModal({
            title: '下载失败',
            content: '更新包下载失败，请检查网络后重试',
            showCancel: false
          })
        }
      }
      
      doDownload()
    },
    
    // 显示下载进度弹窗
    showDownloadProgress() {
      this.downloadProgress = 0
      this.isDownloading = true
      
      // 创建下载进度弹窗
      this.$nextTick(() => {
        this.$refs.downloadModal.open()
      })
    },
    
    // 更新下载进度
    updateDownloadProgress(progress) {
      this.downloadProgress = progress
    },
    
    // 隐藏下载进度弹窗
    hideDownloadProgress() {
      this.isDownloading = false
      this.downloadProgress = 0
      
      if (this.$refs.downloadModal) {
        this.$refs.downloadModal.close()
      }
    },
    
    // 上报版本更新
    async reportUpdate(data) {
      try {
        await reportVersion(data)
      } catch (error) {
        console.error('上报版本信息失败:', error)
      }
    },
    
    clearCache() {
      uni.showModal({
        title: '清除缓存',
        content: '确定要清除所有缓存数据吗？',
        confirmText: '清除',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.performClearCache()
          }
        }
      })
    },
    
    performClearCache() {
      uni.showLoading({ title: '清除中...' })
      
      try {
        // 清除本地存储的缓存数据
        const keysToKeep = ['token', 'userInfo', 'userId', 'userSettings']
        const storageInfo = uni.getStorageInfoSync()
        
        storageInfo.keys.forEach(key => {
          if (!keysToKeep.includes(key)) {
            uni.removeStorageSync(key)
          }
        })
        
        // 重新计算缓存大小
        this.calculateCacheSize()
        
        uni.hideLoading()
        uni.showToast({
          title: '清除成功',
          icon: 'success'
        })
        
        } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '清除失败',
          icon: 'none'
        })
        console.error('清除缓存失败:', error)
      }
    },
    
    exportData() {
      uni.showLoading({ title: '导出中...' })
      
      try {
        // 使用统一的用户信息获取函数
        const userInfo = this.getCurrentUserInfo()
        const exportData = {
          userInfo: userInfo,
          settings: this.settings,
          exportTime: new Date().toISOString()
        }
        
        const dataStr = JSON.stringify(exportData, null, 2)
        
        // #ifdef APP-PLUS
        const filePath = `_doc/user_data_${Date.now()}.json`
        plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
          fs.root.getFile(filePath, { create: true }, (fileEntry) => {
            fileEntry.createWriter((writer) => {
              writer.write(dataStr)
              writer.onwrite = () => {
                uni.hideLoading()
                uni.showToast({
                  title: '导出成功',
                  icon: 'success'
                })
              }
            })
          })
        })
        // #endif
        
        // #ifdef H5
        const blob = new Blob([dataStr], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `user_data_${Date.now()}.json`
        a.click()
        URL.revokeObjectURL(url)
        
        uni.hideLoading()
        uni.showToast({
          title: '导出成功',
          icon: 'success'
        })
        // #endif
        
        } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '导出失败',
          icon: 'none'
        })
        console.error('导出数据失败:', error)
      }
    },
    
    editProfile() {
      uni.navigateTo({ url: '/pages/profile/profile' })
    },
    
    changePassword() {
      uni.showToast({
        title: '功能开发中',
        icon: 'none'
      })
    },
    
    viewAbout() {
      uni.showModal({
        title: '关于 MoeConnect',
        content: `版本：${this.appVersion}\n\n一个充满活力的社交平台，让您与志同道合的朋友们分享生活点滴。\n\n感谢您的使用！`,
        showCancel: false
      })
    },
    
    viewPrivacy() {
      uni.showToast({
        title: '隐私政策页面开发中',
        icon: 'none'
      })
    },
    
    viewTerms() {
      uni.showToast({
        title: '服务条款页面开发中',
        icon: 'none'
      })
    },
    
    togglePushNotification(e) {
      this.settings.pushNotification = e.detail.value
      this.saveSettings()
    },
    
    toggleEmailNotification(e) {
      this.settings.emailNotification = e.detail.value
      this.saveSettings()
    },
    
    togglePublicProfile(e) {
      this.settings.publicProfile = e.detail.value
      this.saveSettings()
    },
    
    toggleAllowSearch(e) {
      this.settings.allowSearch = e.detail.value
      this.saveSettings()
    },
    
    logout() {
      uni.showModal({
        title: '退出登录',
        content: '确定要退出登录吗？',
        confirmText: '退出',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.performLogout()
          }
        }
      })
    },
    
    performLogout() {
      try {
        clearLoginInfo()
          
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }, 1500)
      } catch (error) {
        console.error('退出登录失败:', error)
        uni.showToast({
          title: '退出失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped src="./settings.css"></style> 